//
//  NetworkingHandler.m
//  echo
//
//  Created by dllo on 16/1/25.
//  Copyright © 2016年 Danny. All rights reserved.
//

#import "NetworkingHandler.h"
#import "Reachability.h"
#import <CommonCrypto/CommonDigest.h>
#import <UIKit/UIKit.h>

@implementation NetworkingHandler


+ (void)networkingGetWithUrl:(NSString *)string dicForValue:(NSDictionary *)dic completeHandle:(void (^)(id))block{
#pragma mark - 判断网络状态
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没有网络");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    
    if (isExistenceNetwork) {
        // 字符串转码
        NSString *codeString = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURL *url = [NSURL URLWithString:codeString];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"GET";
        
        if (dic != nil) {
            
            for (NSString *key in dic) {
                
                [request addValue:[dic objectForKey:key] forHTTPHeaderField:key];
                
            }
        }
        
        // session
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            // 回到主线程(GCD).
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (data) {
                    NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
                    NSString *behind = @".data";
                    NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                    
                    
                    NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkingHandler md5HexDigest:string],behind]];
                    
                    [data writeToFile:path  atomically:YES];

                    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    
                    block(result);
                    
                }
                
            });
    
        }];
        
        [dataTask resume];
        
    }else{
        NSLog(@"没有网络");
        NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkingHandler md5HexDigest:string],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
        if (data == nil) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NoNet1" object:nil];
            return;
        }else{
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            
            block(result);
            
        }
    }
}

+ (void)networkingGetWithUrl:(NSString *)string completeHandle:(void (^)(id))block{
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没有网络");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    
    if (isExistenceNetwork) {
        // 字符串转码
        NSString *codeString = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURL *url = [NSURL URLWithString:codeString];
        
        // session
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            // 回到主线程(GCD).
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // 数据解析
                if (data) {
                    NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
                    NSString *behind = @".data";
                    NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                    
                    
                    NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkingHandler md5HexDigest:string],behind]];
                    
                    [data writeToFile:path  atomically:YES];
                    
                    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    
                    
                    // 调用block
                    
                    block(result);
                    
                }
            
            });
            
        }];
        
        [dataTask resume];
        
    }else{
        NSLog(@"没有网络");
        NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        
        NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkingHandler md5HexDigest:string],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
        if (data == nil) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NoNet1" object:nil];
            return;
        }else{
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            
            block(result);
            
        }
    }
}

+ (void)networkingPostWithUrl:(NSString *)string body:(NSString *)str2 dicForValue:(NSDictionary *)dic completeHandle:(void (^)(id))block{
#pragma mark - 判断网络状态
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没有网络");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }

    if (isExistenceNetwork) {
        NSString *codeString = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURL *url = [NSURL URLWithString:codeString];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        request.HTTPBody = [str2 dataUsingEncoding:NSUTF8StringEncoding];
        
        if (dic != nil) {
            
            for (NSString *key in dic) {
                
                [request addValue:[dic objectForKey:key] forHTTPHeaderField:key];
                
            }
        }
        
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (data) {
                    NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
                    NSString *behind = @".data";
                    NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                    
                    
                    NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkingHandler md5HexDigest:str2],behind]];
                    
                    [data writeToFile:path  atomically:YES];
                    
                    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    
                    block(result);
                    
                }
            });
        }];
        
        [dataTask resume];
        
    }else{
        NSLog(@"没有网络");
        NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkingHandler md5HexDigest:str2],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
        if (data == nil) {
        
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NoNet1" object:nil];
            
            
            return;
        }else{
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
            block(result);
            
        }
    }
}

/** md5加密 */
+ (NSString *)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
}

@end
